package com.forum.user.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.forum.common.constant.ErrorCodeEnum;
import com.forum.common.utils.R;
import com.forum.user.entity.ForumUser;
import com.forum.user.service.ForumUserService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    
    @Autowired
    private ForumUserService forumUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //执行controller方法前进行
        /**
         * 1.判断请求的接口路径为HandlerMethod（controller方法）
         * 2.判断token是否为空，如果为空，跳转至登录界面
         * 3.如果token不为空，进行登录验证 logService checkToken
         * 4.认证成功，放行
         */

        if(!(handler instanceof HandlerMethod)){
            //handler可能是RequstResourceHandler
            return true;
        }
        String token = request.getHeader("Authorization");

        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");
        if (StringUtils.isBlank(token)){
            R r =R.error(ErrorCodeEnum.NO_LOGIN_EXCEPTION.getCode() , ErrorCodeEnum.NO_LOGIN_EXCEPTION.getMessage());


            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(JSON.toJSONString(r));
            return false;
        }
        ForumUser forumUser = forumUserService.checkToken(token);
        if (forumUser == null){
            R r =R.error(ErrorCodeEnum.NO_LOGIN_EXCEPTION.getCode() , ErrorCodeEnum.NO_LOGIN_EXCEPTION.getMessage());

            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(JSON.toJSONString(r));
            return false;
        }

//        UserThreadLocal.put(forumUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //如果不删除ThreadLocal，会有内存泄露的的风险
//        UserThreadLocal.remove();
    }
    
}
